package com.bootcamp.servlet.mvc.filter;

import com.bootcamp.servlet.mvc.model.Custom;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(value = "/*")
public class AuthUserHomepageFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 监听访问地址
//        String remoteHost = request.getRemoteHost();
        String remoteAddr = request.getRemoteAddr();
        System.out.println("request from address: " + remoteAddr);

        // 设置request和response编码字符集
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // 判断访问的servlet是否需要登录
        HttpServletRequest req = (HttpServletRequest) request;
        String servletPath = req.getServletPath();
        Custom custom = (Custom) req.getSession().getAttribute("custom");
        List<String> loginServlets = (List<String>) request.getServletContext().getAttribute("loginservlets");

        if (loginServlets.contains(servletPath) && custom != null) {
            // 返回到登录界面,并携带参数
            ((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/store/page");
            return;
        }
        chain.doFilter(request,response);
    }
}
